<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="产品名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
            >
              <el-option
                v-for="item in getProductOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品代码" min-width="150">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productNo" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <dict-tag disabled :type="DICT_TYPE.CRM_PRODUCT_UNIT" :value="row.productUnit" />
        </template>
      </el-table-column>
       <el-table-column label="产品规格" min-width="150">
        <template #default="{ row}">
          <el-form-item  class="mb-0px!">
            <el-input disabled v-model="row.dimension"  />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单价（元）" min-width="150">
<!--        <template #default="{ row, $index }">-->
<!--          <el-form-item :prop="`${$index}.productPrice`" :rules="formRules.productPrice" class="mb-0px!">-->
<!--            <el-input v-model="row.productPrice" placeholder="请输入产品单价" />-->
<!--          </el-form-item>-->
<!--        </template>-->
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="订单价格" min-width="150">
<!--        <template #default="{ row, $index }">-->
<!--          <el-form-item :prop="`${$index}.orderPrice`" :rules="formRules.orderPrice" class="mb-0px!">-->
<!--            <el-input v-model="row.orderPrice" placeholder="请输入订单价格" />-->
<!--          </el-form-item>-->
<!--        </template>-->
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.orderPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.orderPrice"
              controls-position="right"
              :min="0.001"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
<!--        <template #default="{ row, $index }">-->
<!--          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">-->
<!--            <el-input v-model="row.count" placeholder="请输入数量" />-->
<!--          </el-form-item>-->
<!--        </template>-->
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="0.001"
              :precision="3"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="总计价格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" :rules="formRules.totalPrice" class="mb-0px!">
            <el-input v-model="row.totalPrice" placeholder="请输入总计价格" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加产品</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { OrderApi } from '@/api/crm/order'
import { DICT_TYPE } from '@/utils/dict'
import * as ProductApi from '@/api/crm/product'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'

const props = defineProps<{
  orderId: number // 订单编号（主表的关联字段）
  customerId: number // 客户编号（主表的关联字段）
  products: undefined
  disabled: false
}>()
const customerId = computed(() => {
  return props.customerId;
});

const customerId1 = ref();

const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  // orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  orderPrice: [{ required: true, message: '订单价格不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  totalPrice: [{ required: true, message: '总计价格不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const queryParams = reactive({})
const productList = ref<ProductApi.ProductVO[]>([]) // 产品列表
// const productOptions = ref<any[]>([])

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.products,
  async (val) => {
    // 1. 重置表单
    formData.value = val
    // 2. val 非空，则加载数据
    // if (!val) {
    //   return;
    // }
    // try {
    //   formLoading.value = true
    //   formData.value = await OrderApi.getOrderProductListByOrderId(val)
    // } finally {
    //   formLoading.value = false
    // }
  },
  { immediate: true }
)
/** 监听订单产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      if (item.orderPrice != null && item.count != null) {
        item.totalPrice = erpPriceMultiply(item.orderPrice, item.count)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  { deep: true }
)
/** 监听客户变化，查询产品信息 */
// watch(customerId, (newVal) => {
//   alert(newVal);
//   // 根据新值回显数据
//   if(newVal){
//     customerId1.value = newVal
//     // alert(customerId1.value);
//     // queryParams.customerId = newVal
//     // productOptions =  productList.value.find(opt => opt.customerId === newVal);
//     // getProductOptions()
//   }
// });

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    orderId: undefined,
    productId: undefined,
    productPrice: undefined,
    orderPrice: undefined,
    count: undefined,
    dimension: undefined,
    totalPrice: undefined,
  }
  row.orderId = props.orderId as any
  // row.customerId = props.customerId as any
  formData.value.push(row)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnit = product.unit
    row.productNo = product.no
    row.dimension = product.dimension
    row.productPrice = product.price
    // row.orderPrice = product.price
  }
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate })

/** 动态获取客户产品 */
const getProductOptions = computed(() =>{
  if(customerId.value){
    return productList.value.filter((item) => item.customerId == customerId.value)
  }else{
    return productList.value
  }

})

/** 初始化 */
onMounted(async () => {
  if(props.customerId){
    queryParams.customerId = props.customerId
  }
  productList.value = await ProductApi.getProductSimpleList(queryParams)
  // getProductOptions.value =  productList.value
})
</script>
